<template>
    <el-row class="tool-bar">
        
        <!-- 月视图操作 -->
        <el-col :span="11" v-if="viewName === 'dayGridMonth'">
            <el-select size="small" class="select-year" v-model="yearVal" placeholder="请选择年" @change="changeDate($event,0)">
                <el-option
                    v-for="(item,index) in yearData"
                    :key="index"
                    :label="`${item} 年`"
                    :value="item">
                </el-option>
            </el-select>
            <el-button size="small" type="primary" class="prev-btn" icon="el-icon-arrow-left" @click="handlePrevMonth"></el-button>
            <el-select size="small" class="select-month" v-model="monthVal" placeholder="请选择月" @change="changeDate($event,1)">
                <el-option
                    v-for="(item,index) in 12"
                    :key="index"
                    :label="`${item} 月`"
                    :value="item">
                </el-option>
            </el-select>
            <el-button size="small" type="primary" class="next-btn" icon="el-icon-arrow-right" @click="handleNextMonth"></el-button>
            <el-button size="small" @click="backToday">回到今天</el-button>
        </el-col>

        <!-- 周视图操作 -->
        <el-col :span="11" v-else>
            <el-select size="small" class="select-term" v-model="termId" placeholder="请选择学期" @change="selectTerm">
                <el-option
                    v-for="item in termData"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                </el-option>
            </el-select>
            <el-button size="small" type="primary" class="prev-btn" icon="el-icon-arrow-left" :disabled="weekVal === 1" @click="handleWeek(-1)"></el-button>
            <el-select size="small" class="select-week" v-model="weekVal" placeholder="请选择周" @change="selectWeek">
                <el-option
                    v-for="(item,index) in weeks"
                    :key="index"
                    :label="`第 ${item} 周`"
                    :value="item">
                </el-option>
            </el-select>
            <el-button size="small" type="primary" class="next-btn" icon="el-icon-arrow-right" :disabled="weekVal === weeks" @click="handleWeek(1)"></el-button>
            <el-button size="small" @click="backToday">回到今天</el-button>
        </el-col>

        <!-- 日期字符串 -->
        <el-col :span="10"><h2 class="time-title">{{timeStr}}</h2></el-col>

        <!-- 切换视图按钮组 -->
        <el-col :span="3" class="view-btns">
            <el-button-group :class="`${viewName}-class`">
                <el-button type="primary" size="small" @click="changeView('dayGridMonth')">月</el-button>
                <el-button type="primary" size="small" @click="changeView('timeGridWeek')">周</el-button>
            </el-button-group>
        </el-col>

    </el-row>
</template>

<script>
import moment from 'moment';
export default {
	data() {
        return {
            timeStr:'',
            viewName:'dayGridMonth',

            monthData:[],
            monthVal:'',
            yearData:[],
            yearVal:'',

            termData:[],
            termId:'',
            weeks:0,
            weekVal:1,                        
            oldWeekVal:null,   
            eventColors: ['#bcecff', '#c3f6cf', '#dde2ff', '#ffe0fb'],                    
        }
    },
    created () {
        this.getDefault();
        this.getTeam();
    },
    mounted () {
        this.getSchedule();
    },
    watch: {

    },
    computed: {
        calendarApi(){
            return this.$parent.$refs.fullCalendar.getApi();
        },
    },
    methods:{
        //公共-获取用户的日程
		getSchedule() {
			const create_id = this.$store.getters.userInfo.id;
			let params = {};
			let success = res => {
                this.changeCalendarData( res.data);
			};
			if (this.viewName === 'dayGridMonth') {//月视图
				params = {
					create_id: create_id,
					time_type: '1',
					select_time: `${this.yearVal}-${this.monthVal}`,
				};
			} else {//周视图
				params = {
					create_id: create_id,
					time_type: '2',
					term_id: this.termId,
					weeks: this.weekVal,
				};
			}
			this.$ajax({
				url: 'api/schedule/schedule_list',
				method: 'get',
				params,
				func: { success: success }
			});
        },


        //公共-转成符合日历插件的数据格式：
		changeCalendarData(obj) {
			let event_data = [];
			for (var key in obj) {
				if (obj[key].length !== 0) {
					obj[key].forEach((val, inx, arr) => {
						event_data.push(val);
					});
				}
            }
            let ids = [];
            event_data = event_data.filter(x => {
                if(!ids.includes(x.id)){
                    ids.push(x.id);
                    let newPropty = {
                        title: x.content,
                        start: x.start_time,
                        end: x.end_time,
                        backgroundColor: this.eventColors[x.type - 1],
                        textColor:'#000',
                        borderColor:'#fff',
                        className:x.is_import === 1 ? `el-icon-star-on eventClass${x.type - 1}` : `eventClass${x.type - 1}`,
                    };
                    return Object.assign(x,newPropty);
                }
            })
            this.$parent.calendarOptions.events = event_data;
        },
        //公共-回到今天按钮
        backToday(){
            this.calendarApi.today();
            this.setTimeTitle();
            this.getSchedule();
        },

        // 月视图-页面初始化，顶部各项的默认值
        getDefault(){
            const nowDate = moment();
            this.yearVal = + nowDate.format('YYYY');
            this.yearData = [this.yearVal - 1,this.yearVal,this.yearVal + 1];
            this.monthVal = + nowDate.format('MM');
            this.timeStr = nowDate.format('YYYY年MM月');
        },

        //月视图- 年/月 select框：val年或月的值；type:0是年，1是月
        changeDate(val,type){
            let date = this.calendarApi.getDate();
            date = moment(date).format('YYYY-MM-DD').split('-');//获取现在视图中年月日的字符串
            date[type] = type === 1 && val < 10 ? `0${val}` : val;//根据年、月不同的select，把字符串中对应位置的年/月值替换掉，注意月份值10的要补0
            date = date.join('-');
            this.gotoDate(date);
            this.setTimeTitle();
            this.getSchedule();
        },

        // 月视图-上一月
        handlePrevMonth(){
            this.calendarApi.prev();
            this.setTimeTitle();
        },
        // 月视图-下一月
		handleNextMonth(){
            this.calendarApi.next();
            this.setTimeTitle();
        },
        //公共-设置顶部栏中间的日期
        setTimeTitle(){
            // console.log(this.calendarApi ,this.calendarApi.getDate())
            if(this.viewName === 'dayGridMonth'){//月视图
                let timeStr = this.calendarApi.getDate();
                timeStr = moment(timeStr);
                this.timeStr =  timeStr.format('YYYY年MM月');
                this.yearVal =  + timeStr.format('YYYY');
                this.monthVal =  + timeStr.format('MM');
            }else{//周视图
                const viewTitle = this.calendarApi.currentData.viewTitle;
                this.timeStr = viewTitle;
                // 截取时间范围的开始时间：如从2020年10月5日 – 11日截取出2020-10-5
                let start = viewTitle.split('日')[0];
                const reg = /[\u4e00-\u9fa5]/g;
                start = start.replace(reg,'-');
                // if(this.oldWeekVal !== null && this.weekVal === 1){ //非初始化的切换回第一周
                //     console.log(this.termData,this.termId,this.oldWeekVal,this.weekVal)
                //     console.log(start)

                // }else{
                    this.termData.map(x => {
                        if(this.isDuringDate(start,x.start_time,x.end_time)){
                            this.termId = x.id;
                            this.weeks = x.weeks;
                            this.weekVal = this.getWeekTurn(x.start_time,start);
                            this.oldWeekVal = this.weekVal;
                        }
                    })
                // }
            }
        },
        // 周视图-判断某个日期compareDate是否在日期范围:beginDate~endDate内
        isDuringDate(compareDate,beginDate,endDate) {
            // console.log(compareDate,beginDate,endDate)
            const c = new Date(compareDate);
            const b = new Date(beginDate);
            const e = new Date(endDate);
            if (c >= b && c <= e) {
                return true;
            }
            return false;
        },
        // 周视图-根据某个日期和学期首日，判断此日期在这个学期的第几周
        getWeekTurn(termStart,curDate){
            let diffDate = new Date(curDate) - new Date(termStart);
            diffDate = Math.ceil(diffDate) / (24*60*60*1000);
            return Math.ceil(diffDate / 7) + 1;  
        },
        //公共-设置calander日期
        gotoDate(date){
			this.calendarApi.gotoDate( date );
        },
        // 公共-切换视图
        changeView(viewName){
            if(viewName === 'timeGridWeek' && this.termData.length === 0){
                this.$message.warning('您的账号未绑定学期，请联系管理员在后台创建学期,才能查看周视图');
                return;
            }
            this.viewName = viewName;
            this.calendarApi.changeView( viewName );
            this.backToday();
        },
        //周视图-获取当前用户的学期  
        getTeam() {
			let success = res => {
                let data = res.data;
                if(data && data.length > 0){
                    this.termData = data.map(x => {
                       x.label = `${x.start_year}-${x.end_year} ${x.semester_name}`;
                       return x;
                    })
                }
			};
			this.$ajax({
				url: 'api/term/term_list',
				method: 'get',
				params: {},
				func: { success: success }
			});
        },
        // 周视图-选择学期
		selectTerm(e) {
            this.termData.map(x => {
                if(x.id === e){
                    this.weeks = x.weeks;
                    this.weekVal = 1;
                    this.selectWeek(1);
                    this.calendarApi.gotoDate(x.start_time);
                }
            })
        },     
        // 周视图-上一周  / 下一周 
        handleWeek(arrow){
            let newVal = this.weekVal + arrow;
            if((arrow === -1 && newVal > 0) || (arrow === 1 && newVal <= this.weeks)){
                this.weekVal = newVal;
            }
            this.gotoWeek(arrow,1);
        },
        // 周视图- 跳到某一周 arrow：相对于当前的周，前面的周-1，后面的1  ，num：相隔几周
        gotoWeek(arrow,num){
            // console.log(arrow,num,this.calendarApi.view)
            const currentMonday = this.calendarApi.view.currentStart.getTime();
            let result = arrow === -1 ? (currentMonday - 3600 * 1000 * 24 * 7 * num) : (currentMonday + 3600 * 1000 * 24 * 7 * num);
            const mondayVal = moment(result).format('YYYY-MM-DD');
            console.log(mondayVal)
            this.calendarApi.gotoDate(mondayVal);//跳到上一周，或者下一周（跳周一的日期即可）
            this.setTimeTitle();
            this.getSchedule();
        },
        // 周视图-选择周
        selectWeek(val){
            if(val === this.oldWeekVal){
                this.oldWeekVal = val;
            }else{
                const arrow = val > this.oldWeekVal ? 1 : -1;
                const num = val > this.oldWeekVal ? (val - this.oldWeekVal) : (this.oldWeekVal - val);
                this.gotoWeek(arrow,num);
                this.oldWeekVal = val;
                console.log(arrow,num, val , this.oldWeekVal)
            }
        },
    }
}
</script>

<style lang="scss">
    .select-year,.select-term{
        margin-right: 20px;
    }
    .select-year{
        width: 120px;
    }
    .select-term{
        width: 240px;
    }
    .select-month,.select-week{
        .el-input__inner{
            border-radius: 0;
        }
    }    
    .select-month{
        width: 80px;
    }
    .select-week{
        width: 120px;
    }
    .prev-btn{
        border-radius: 3px 0 0 3px;
    }
    .next-btn{
        border-radius: 0 3px 3px 0;
        margin-right: 10px;
    }
    .time-title{
        line-height: 1.7;
        font-size: 18px;
        font-weight: 600;
    }
    .view-btns{
        text-align: right;
    }
    .dayGridMonth-class{
        .el-button:first-child {
            color: #FFF;
            background-color: #409EFF;
            border-color: #409EFF;
        }
        .el-button:last-child {
            color: #000;
            background-color: #FFF;
            border-color: #dcdfe6;
        }
    }
    .timeGridWeek-class{
        .el-button:first-child {
            color: #000;
            background-color: #FFF;
            border-color: #dcdfe6;
        }
        .el-button:last-child {
            color: #FFF;
            background-color: #409EFF;
            border-color: #409EFF;
        }
    }
</style>